package main

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"strings"
)

type CUser struct {
	gorm.Model
	Name string
	Info Args
}
type Args []string

//Value 写入自定义类型到数据库.u是Go中类型，driver.Value是将Go中的类型转化为后的值，并写入数据
func (a Args) Value() (driver.Value, error) {
	if len(a) > 0 {
		resStr := a[0]
		for _, value := range a[1:] {
			resStr += "," + value
		}
		return resStr, nil
	}
	return "", nil
}

//Scan 读取数据库字段，转化为Go中的类型.将value转化为Go中的结构后，并写入u
func (a *Args) Scan(value interface{}) error {
	str, ok := value.([]byte)
	if !ok {
		return errors.New("不匹配的数据类型")
	}
	*a = strings.Split(string(str), ",")
	return nil
}
func main() {
	dsn := "root:hedaodao@(127.0.0.1:3306)/gorm_class?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "test_",
			SingularTable: false,
		},
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(err)
	}

	//迁移时，只迁移HeadMaster就会同时创建两个表
	db.AutoMigrate(&CUser{})
	//db.Create(&CUser{
	//	Name: "frist",
	//	Info: Args{
	//		"1",
	//		"2",
	//	},
	//})
	var c CUser
	db.First(&c)
	fmt.Printf("%#v\n", c.Info)

}
